package cn.tedu.demo.service.impl;

import cn.tedu.demo.ex.ServiceException;
import cn.tedu.demo.mapper.RoomTypeMapper;
import cn.tedu.demo.pojo.entity.User;
import cn.tedu.demo.pojo.entity.UserInfo;
import cn.tedu.demo.pojo.vo.RoomTypeDetailListVO;
import cn.tedu.demo.pojo.vo.RoomTypeVO;
import cn.tedu.demo.pojo.vo.UserVO;
import cn.tedu.demo.service.IRoomTypeService;
import cn.tedu.demo.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Slf4j
@Service
public class RoomTypeServiceImplement implements IRoomTypeService {
    @Autowired
    RoomTypeMapper roomTypeMapper;

    @Override
    public RoomTypeVO getStandardById(Long id, HttpServletRequest request) {
        log.debug("进入房型业务层，开始处理【根据房型id获取房型详情】的业务");
        HttpSession session = request.getSession();
        UserVO user = (UserVO) session.getAttribute("user");
        log.debug("判断用户是否登录，如果登录，执行增加点击数系列的操作");
        if(user!=null){
            log.debug("设置点击数增加条件为：click + 房型id + 用户id，只有该条件在session中不存在时才会执行增加点击数");
            String info= (String) session.getAttribute("click"+id+user.getId());
            log.debug("判断是否需要增加点击数");
            if(info==null){
                session.setAttribute("click"+id+user.getId(),"clicked");
                int rows = roomTypeMapper.updateClickNums(id);
                if(rows!=1){
                    String message="房型点击数增加失败";
                    log.warn(message);
                    throw new ServiceException(ServiceCode.ERROR_UPDATE,message);
                }
            }
        }
        RoomTypeVO roomTypeVO = roomTypeMapper.getStandardById(id);
        roomTypeVO.setSpareRoomCount(roomTypeMapper.countSpareRoomCount(id));
        roomTypeVO.setOrderNums(roomTypeMapper.countOrderNums(id));
        log.debug("通过检查，房型存在");
        return roomTypeVO;
    }

    @Override
    public List<RoomTypeDetailListVO> getList() {
        log.debug("进入房型业务，开始处理【获取房型详情列表】的业务");

        List<RoomTypeDetailListVO> roomTypeListVO = roomTypeMapper.getList();

        return roomTypeListVO;
    }
}
